﻿using AutoMapper;
using DFGK.IRepository;
using DFGK.IService;
using DFGK_WMS.Model.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DFGK.Service
{
    public class MaterialKeyService : BaseService, IMaterialKeyService
    {
        private readonly IMaterialKeyRepository _materialKeyRepository;
        private readonly IUnitOfWork _unitOfWork;
        public MaterialKeyService(IMapper mapper, IUnitOfWork unitOfWork, IMaterialKeyRepository _materialKeyRepository) : base(mapper)
        {
            this._materialKeyRepository = _materialKeyRepository;
            _unitOfWork = unitOfWork;
        }

        public bool AddMaterialKey(MaterialKey m)
        {
            var obj = _materialKeyRepository.QueryIsEntityWhere(x => x.BatchNo == m.BatchNo);
            if (obj != null)
            {
                return false;
            }
            //质量状态设定为合格
            m.QualityState = 1;
            _materialKeyRepository.AddEntity(m);
            return _unitOfWork.SaveChangesEntity();
        }

        public bool DelMaterialKey(long mid)
        {
            var mobj = _materialKeyRepository.QueryEntityById(mid);

            if (mobj != null)
            {
                _materialKeyRepository.DelEntity(mobj);
            }
            return _unitOfWork.SaveChangesEntity();
        }

        public MaterialKey? GetMaterialKeyById(long mid)
        {
            return _materialKeyRepository.QueryEntityById(mid);
        }

        public List<MaterialKey> GetMaterialKeyList(string? mname, int pageIndex, int pageSize, out int totalCount)
        {
            var list = _materialKeyRepository.GetEntityAlls();

            if (!string.IsNullOrEmpty(mname))
            {
                list = list.Where(x => x.MaterialName.Contains(mname));
            }
            var lists = _materialKeyRepository.GetEntityAlls(list, pageIndex, pageSize, out totalCount, x => x.CreateDate, false);
            return lists.ToList();
        }

        public bool UpdMaterialKey(MaterialKey m)
        {
            var list =_materialKeyRepository.QueryIsEntityWhere(x => x.Id != m.Id && x.BatchNo == m.BatchNo);

            if (list != null)
            {
                return false;
            }

            _materialKeyRepository.UpdEntity(m);
            return _unitOfWork.SaveChangesEntity();
        }
    }
}
